package com.mayikt.generator;

import com.mayikt.constants.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @Classname OrderNoUtils
 * @Description SpringBoot SpringCloud 构建微服务电商平台。
 * @Created by CHEN JIN LONG
 * @Date 2019/1/22 20:38
 * @Version 1.0
 */
@Component
@Slf4j
public class OrderNoGenerator {

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * @param key key
     * @return
     * @Description: 获取自增长值
     */
    public Long getIncr(String key) {
        RedisAtomicLong redisAtomicLong = new RedisAtomicLong(Constants.ORDERNO_KEY_VALUE, redisTemplate.getConnectionFactory());
        //设置初始值 切记这里不要开启
        //redisAtomicLong.set(0);
        //集群时设置步长9
        //redisAtomicLong.addAndGet(9);
        Long increment = redisAtomicLong.getAndIncrement();
        //这里设置Key过期时间
        redisAtomicLong.expire(1, TimeUnit.SECONDS);
        return increment;
    }

    /**
     * 生成订单号，自动补0
     *
     * @param key
     * @return
     */
    public String generateOrderNo(String key) {
        Long increment = getIncr(key);
        String orderNo = prefix() + "-" + String.format("%1$05d", increment);
        return orderNo;
    }

    public String prefix() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        return sdf.format(date);
    }

    /**
     * @param key   key
     * @param value 当前值
     * @Description: 初始化自增长值
     */
    public void setIncr(String key, int value) {
        RedisAtomicLong counter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        counter.set(value);
        counter.expire(0, TimeUnit.SECONDS);
    }

}
